package org.arch_learn.rpc.nz_rpc.configuration;

import org.apache.curator.framework.CuratorFramework;
import org.arch_learn.rpc.nz_rpc.endpoint.NettyRpcClient;
import org.arch_learn.rpc.nz_rpc.quartz.ScheduledJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@EnableScheduling
@ConditionalOnBean(name = "nettyRpcClients")
@AutoConfigureAfter(RPCAutoConfiguration.class)
public class ScheduleTaskAutoConfiguration {
    @Autowired
    private CuratorFramework curatorFramework;
    @Autowired
    private ConcurrentHashMap<String, List<NettyRpcClient>> nettyClientsMap;

    @Bean
    public JobDetail jobDetail() {
        JobDetail jobDetail = JobBuilder.newJob(ScheduledJob.class)
                .withIdentity("jobDetail")
                .storeDurably()
                .build();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        jobDataMap.putIfAbsent("nettyRpcClientsMap", nettyClientsMap);
        jobDataMap.putIfAbsent("client", curatorFramework);
        return jobDetail;
    }

    /**
     * 触发器，每间隔一段时间触发定时任务
     *
     * @param jobDetail 具体执行的定时任务
     * @return
     */
    @Bean
    public Trigger jobTrigger(@Qualifier("jobDetail") JobDetail jobDetail) {
        ScheduleBuilder scheduleBuilder = SimpleScheduleBuilder
                .simpleSchedule()
                .withIntervalInSeconds(5) //定时任务间隔时间
                .repeatForever(); //触发器无限循环触发
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity("jobTrigger")
                .withSchedule(scheduleBuilder)
                .build();
    }
}
